package com.nlx.notes.support.helper.gold;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.nlx.notes.configuer.thread.ScheduledThreadConfig;
import com.nlx.notes.module.core.consts.RedisConst;
import com.nlx.notes.support.helper.redis.RedisHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class GoldPriceCalculateHelper {

    final RedisHelper redisHelper;

    /**
     * 国内价格
     */
    private static  BigDecimal CN_CURRENT_GOLD_PRICE = null;

    /**
     * 国际价格
     */
    private static BigDecimal INTER_CURRENT_GOLD_PRICE = null;

    private static final long DELAY = 5;

    private static BigDecimal GOLD_PREMIUM = new BigDecimal("0");

    /**
     * 国内金价
     */
    private static String GOLD_PRICE_QUER_URL = "https://api.jijinhao.com/sQuoteCenter/realTime.htm?code=JO_9753&_={timestamp}";

    /**
     * 国际金价
     */
    private static String GOLD_IN_PRICE_QUERY_URL = "https://api.jijinhao.com/sQuoteCenter/realTime.htm?code=JO_92233&isCalc=true&_={timestamp}";


     private static final LocalTime MORNING_START = LocalTime.of(9, 0);
    private static final LocalTime MORNING_END = LocalTime.of(11, 30);

    private static final LocalTime AFTERNOON_START = LocalTime.of(13, 30);
    private static final LocalTime AFTERNOON_END = LocalTime.of(15, 30);

    private static final LocalTime NIGHT_START = LocalTime.of(20, 0);
    private static final LocalTime NIGHT_END = LocalTime.of(2, 30);

    public static boolean isWithinTradingTime(LocalTime time){
        boolean inMorning = !time.isBefore(MORNING_START) && !time.isAfter(MORNING_END);
        boolean inAfternoon = !time.isBefore(AFTERNOON_START) && !time.isAfter(AFTERNOON_END);
        // 判断是否在夜盘区间（注意跨天）
        boolean inNight = time.isAfter(NIGHT_START) || time.isBefore(NIGHT_END);
        return inMorning || inAfternoon || inNight;
    }


    public static void startGoldPriceCalculate() {
        ScheduledThreadConfig.getSCHEDULER().scheduleAtFixedRate(GoldPriceCalculateHelper::calculateGoldPrice,0,DELAY, TimeUnit.SECONDS);
    }


    /**
     * 获取当前黄金价格
     * @return BigDecimal
     */
    public static BigDecimal getCurrentGoldPrice() {
        boolean flag = isWithinTradingTime(LocalTime.now());
        if(flag){
            return CN_CURRENT_GOLD_PRICE;
        }
        return INTER_CURRENT_GOLD_PRICE.add(GOLD_PREMIUM).subtract(new BigDecimal("0.5"));
    }

    /**
     * 获取黄金今日的开始价格
     * @return
     */
    public  BigDecimal getCurrentGoldStartPrice() {
        BigDecimal startGoldPrice = redisHelper.getKey(RedisConst.Token.gold.CURRENT_DAY_START_PRICE_KEY,BigDecimal.class);
        if(null == startGoldPrice){
            calculateStartGoldPrice();
            return getCurrentGoldStartPrice();
        }
        return startGoldPrice;
    }


    /**
     * 计算黄金溢价
     */
    @Scheduled(cron = "0 30 2,11,15 * * *")
    public  void calculateGoldPremium(){
        calculateGoldCNPrice();
        calculateGoldInternationalPrice();
        GOLD_PREMIUM = CN_CURRENT_GOLD_PRICE.subtract(INTER_CURRENT_GOLD_PRICE);
        log.info("黄金溢价：{}",GOLD_PREMIUM);
    }

    @Scheduled(cron = "0 0 0 * * ?")
    public  void calculateStartGoldPrice(){
        BigDecimal startGoldPrice = getCurrentGoldPrice();
        if(null != startGoldPrice){
            redisHelper.setValue(RedisConst.Token.gold.CURRENT_DAY_START_PRICE_KEY,startGoldPrice,25,TimeUnit.HOURS);
        }
    }




    private static  void  calculateGoldPrice(){
        calculateGoldCNPrice();
        calculateGoldInternationalPrice();
        //log.info("当前黄金价格：{}",getCurrentGoldPrice());
    }







    private static void calculateGoldCNPrice() {
        //log.info("start pull gold price");
        try {
            String timestamp = System.currentTimeMillis() + "";
            String url = GOLD_PRICE_QUER_URL.replace("{timestamp}", timestamp);
            Map<String, String> hearderMap = new HashMap<>();
            hearderMap.put("accept", "*/*");
            hearderMap.put("referer", "https://quote.cngold.org/");
            hearderMap.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36");
            HttpResponse execute = HttpRequest.get(url).addHeaders(hearderMap).execute();
            String result = execute.body().split("=")[1].trim();
            String[] strSpilt = result.split(",");
            CN_CURRENT_GOLD_PRICE = new BigDecimal( String.format("%.2f",Double.parseDouble(strSpilt[3])));
            CN_CURRENT_GOLD_PRICE = CN_CURRENT_GOLD_PRICE.subtract(new BigDecimal("0.5"));
            //log.info("CN_CURRENT_GOLD_PRICE：{}", CN_CURRENT_GOLD_PRICE);
        }catch (Exception e){
            log.error("获取实时黄金价格异常，错误信息 ->",e);
            CN_CURRENT_GOLD_PRICE = null;
        }
    }


    private static void calculateGoldInternationalPrice() {
        //log.info("start pull gold price");
        try {
            String timestamp = System.currentTimeMillis() + "";
            String url = GOLD_IN_PRICE_QUERY_URL.replace("{timestamp}", timestamp);
            Map<String, String> hearderMap = new HashMap<>();
            hearderMap.put("accept", "*/*");
            hearderMap.put("referer", "https://quote.cngold.org/");
            hearderMap.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36");
            HttpResponse execute = HttpRequest.get(url).addHeaders(hearderMap).execute();
            String result = execute.body().split("=")[1].trim();
            String[] strSpilt = result.split(",");
            INTER_CURRENT_GOLD_PRICE = new BigDecimal( String.format("%.2f",Double.parseDouble(strSpilt[3])));
            //log.info("INTER_CURRENT_GOLD_PRICE：{}", INTER_CURRENT_GOLD_PRICE);
        }catch (Exception e){
            log.error("获取实时黄金价格异常，错误信息 ->",e);
            CN_CURRENT_GOLD_PRICE = null;
        }
    }




}
